package com.want.evenchat.model.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.want.evenchat.model.bean.UserInfo;
import com.want.evenchat.model.db.UserAccountDB;

/**
 * Created by Want on 2018/5/3.
 */

public class UserAccountDAO {

    private final UserAccountDB mHelper;

    //用户帐号数据库的操作类
    public UserAccountDAO(Context context) {
        //创建一个数据库
        mHelper = new UserAccountDB(context);
    }

    //添加用户到数据库
    public void addAccount(UserInfo user){
        //获取数据库对象
        SQLiteDatabase db = mHelper.getReadableDatabase();

        //执行添加操作
        ContentValues values = new ContentValues();
        values.put(UserAccountTable.COL_HXID , user.getHxid());
        values.put(UserAccountTable.COL_NAME , user.getName());
        values.put(UserAccountTable.COL_NICK, user.getNick());
        values.put(UserAccountTable.COL_PHOTO , user.getPhoto());

        db.replace(UserAccountTable.TAB_NAME, null ,values);
    }

    //根据环信id获取所以用户信息
    public UserInfo getAccountByHxid(String hxid){
        //1.获取数据库对象
        SQLiteDatabase db = mHelper.getReadableDatabase();

        //2.执行查询语句
        String sql = "select * from " + UserAccountTable.TAB_NAME + " where " + UserAccountTable.COL_HXID + "=?";
        Cursor cursor = db.rawQuery(sql , new String[]{hxid});

        UserInfo userInfo = null;
        if (cursor.moveToNext()){//判断下面是否有数据
            userInfo = new UserInfo();

            //把COL_HXID列返回
            userInfo.setHxid(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_HXID)));
            userInfo.setName(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_NAME)));
            userInfo.setNick(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_NICK)));
            userInfo.setPhoto(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_PHOTO)));
        }

        //3关闭资源
        cursor.close();

        //4.返回数据
        return userInfo;
    }

}
